<?php
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use app\admin\model\SiteModel;
use think\Db;

class SiteController extends AdminBaseController
{
    /**
     * 站点管理
     * @adminMenu(
     *     'name'   => '站点管理',
     *     'parent' => 'admin/Setting/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 30,
     *     'icon'   => '',
     *     'remark' => '站点管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $siteModel = new SiteModel();

        $sites = $siteModel->select();
        $this->assign('sites', $sites);

        $actions = ['add', 'edit', 'delete'];
        $this->assign('actions', actions_check($this->request->module().'/'.$this->request->controller().'/', $actions));

        return $this->fetch();

    }

    /**
     * 添加站点
     * @adminMenu(
     *     'name'   => '添加站点',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加站点',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 添加站点提交保存
     * @adminMenu(
     *     'name'   => '添加站点提交保存',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加站点提交保存',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {

        if ($this->request->isPost()) {
            $param  = $this->request->post();
            $result = $this->validate($param, 'Site');
            if ($result !== true) {
                $this->error($result);
            }

            $siteModel = new SiteModel();
            $siteId    = $siteModel->allowField(true)->insertGetId($param);

            if( $siteId ){
                $dConfig = new \dconfig\Dconfig();  //实例化

                $config = ['cmf_default_theme' => ''];
                $size   = $dConfig
                       -> file(CMF_ROOT.'data/conf/site/'.$siteId.'.php')
                       -> note('站点配置文件')
                       -> to_require_one($config);
                if (!$size) {
                    $siteModel->where('site_id', $siteId)->delete();
                    $this->error('站点配置文件创建失败，请检查config目录权限');
                }

                // 若站点域名不为空
                if( !empty($param['domain']) ){
                    $domain  = require CMF_ROOT.'data/conf/domain.php'; // 加载站点域名配置文件
                    $domain[$param['domain']] = $siteId;
                    $size = $dConfig
                         -> file(CMF_ROOT.'data/conf/domain.php')
                         -> note('站点域名文件')
                         -> to_require_one($domain);
                    if (!$size) {
                        $siteModel->where('site_id', $siteId)->delete();
                        $this->error('网站域名文件创建失败，请检查config目录权限');
                    }
                }

                // 拷贝默认站点配置信息等
                $optionList = db('option')
                           -> field('option_name,option_value')
                           -> where('site_id', 1)
                           -> select();

                foreach ($optionList as $k => $v) {
                    $data = [
                        'option_name'  => $v['option_name'],
                        'option_value' => $v['option_value'],
                        'site_id'      => $siteId,
                    ];
                    db('option')->insert($data);
                }

                // 创建一个主导航
                $data = [
                    'is_main' => 1,
                    'name'    => '主导航',
                    'remark'  => '主导航',
                    'site_id'  => $siteId,
                ];
                db('nav')->insert($data);
            }

            $this->success(lang("ADD_SUCCESS"), url("site/index"));
        }
    }

    /**
     * 编辑站点
     * @adminMenu(
     *     'name'   => '编辑站点',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑站点',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id         = $this->request->param("id", 0, 'intval');
        $siteModel  = new SiteModel();
        $objSiteCat = $siteModel->find($id)->toArray();
        $this->assign($objSiteCat);

        return $this->fetch();
    }


    /**
     * 编辑站点提交保存
     * @adminMenu(
     *     'name'   => '编辑站点提交保存',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑站点提交保存',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        $param  = $this->request->post();
        $result = $this->validate($param, 'Site');
        if ($result !== true) {
            $this->error($result);
        }

        $siteModel = new SiteModel();
        $result    = $siteModel->allowField(true)->update($param);
        
        if( $result ){
            $list    = $siteModel->where('domain','neq','')->column('domain,site_id');
            $dConfig = new \dconfig\Dconfig();  //实例化
            $size    = $dConfig
                    -> file(CMF_ROOT.'data/conf/domain.php')
                    -> note('站点域名文件')
                    -> to_require_one($list);
            if (!$size) {
                $this->error('站点配置文件创建失败，请检查config目录权限');
            }
        }

        $this->success(lang("EDIT_SUCCESS"), url("site/index"));

    }

    /**
     * 删除站点
     * @adminMenu(
     *     'name'   => '删除站点',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除站点',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $id        = $this->request->param("id", 0, "intval");


        
        if (empty($id)) {
            $this->error(lang("NO_ID"));
        }

        if ($id == 1) {
            $this->error('主站点不能删除');
        }

        $siteModel = new SiteModel();

        // 删除数据库记录
        $siteModel->where('site_id', $id)->delete();

        // 清除站点相应表的数据
        $tables = Db::query("show tables");// 取得所有的表名
        foreach( $tables as $k=>$v)
        {
            $tableName = $v['Tables_in_'.config('database.database')];
            $fields    = Db::query('show fields from '.$tableName);    //取得所有字段

            foreach ($fields as $key => $val) {
                // 若数据表存在site_id字段，则删除此站点在该数据表的数据
                if( $val['Field'] == 'site_id' ){
                    Db::table($tableName)->where($val['Field'], $id)->delete();
                }
            }
            
        }
        // $models = ['auth_access', 'category_priv', 'option', 'nav', 'nav_menu', 'slide', 'slide_item', ''];
        // $this->clearData($id, $models);

        // 删除站点配置文件
        if( is_file(CMF_ROOT.'data/conf/site/'.$id.'.php') ){
            unlink(CMF_ROOT.'data/conf/site/'.$id.'.php');
        }

        // 更新站点域名配置文件
        $list    = $siteModel->where('domain','neq','')->column('domain,site_id');
        $dConfig = new \dconfig\Dconfig();  //实例化
        $dConfig->file(CMF_ROOT.'data/conf/domain.php')->note('站点域名文件')->to_require_one($list);

        $this->success(lang("DELETE_SUCCESS"), url("site/index"));
    }


    /**
     * 切换站点
     * @adminMenu(
     *     'name'   => '切换站点',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '切换站点',
     *     'param'  => ''
     * )
     */
    public function select()
    {
        $id    = $this->request->param("id", 0, "intval");
        $count = db('site')->where('site_id', $id)->count();

        if( $count ){
            session('SITE_ID', $id);
            $this->redirect(url("admin/Index/index"));
        }else{
            $this->error('站点不存在');
        }
    }

    //清除站点相应表的数据
    protected function clearData($siteId, $models)
    {
        foreach ($models as $v) {
            db($v)->where('site_id', $siteId)->delete();
        }
    }
}
